package com.android.sdcard.folder;

import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.sdcard.folder.FolderComponent.Type;
import com.bhprod.guitartrack.R;

public class FileArrayAdapter extends ArrayAdapter<FolderComponent> {

	private Context c;
	private int id;
	private List<FolderComponent> items;

	public FileArrayAdapter(Context context, int textViewResourceId, List<FolderComponent> objects) {
		super(context, textViewResourceId, objects);
		c = context;
		id = textViewResourceId;
		items = objects;
	}

	public FolderComponent getItem(int i) {
		return items.get(i);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater vi = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(id, null);
		}

		final FolderComponent item = items.get(position);

		if (item != null) {
			TextView tvName = (TextView) v.findViewById(R.id.TextViewName);
			TextView tvData = (TextView) v.findViewById(R.id.TextViewData);
			TextView tvDate = (TextView) v.findViewById(R.id.TextViewDate);

			ImageView icon = (ImageView) v.findViewById(R.id.fd_Icon1);

			if (Type.FOLDER.equals(item.getType())) {
				String uri = "drawable/directory_icon";
				int imageResource = c.getResources().getIdentifier(uri, null, c.getPackageName());
				Drawable image = c.getResources().getDrawable(imageResource);
				icon.setImageDrawable(image);
			} else if (Type.FILE.equals(item.getType())) {
				Bitmap bmp = BitmapFactory.decodeFile(item.getPath());
				if (bmp == null) {
					String uri = "drawable/file_icon";
					int imageResource = c.getResources().getIdentifier(uri, null, c.getPackageName());
					Drawable image = c.getResources().getDrawable(imageResource);
					icon.setImageDrawable(image);
				} else {
					icon.setImageBitmap(bmp);
				}
			}
			if (tvName != null)
				tvName.setText(item.getName());
			if (tvData != null)
				tvData.setText(item.getData());
			if (tvDate != null)
				tvDate.setText(item.getDate());

		}
		return v;
	}

}
